<!-- 提交报告 -->
<template>
  <div class="UploadReport">
    <el-dialog
      :visible="visible"
      :close-on-click-modal="false"
      width="700px"
      :modal-append-to-body="false"
      :show-close="false"
      :top="`8vh`"
    >
      <BaseDialogHead
        slot="title"
        title="提交报告"
        icon-class="chuangjiankuangchi16px"
        @handleCloseDialog="handleCloseDialog"
      />

      <div class="fromcontent">
        <el-form
          ref="ruleForm"
          v-loading="loading"
          label-position="left"
          :model="reportForm"
          :rules="rules"
          label-width="100px"
          class="PersonalInfo__ruleForm"
        >
          <el-form-item label="汇报人" prop="user">
            <el-input
              v-model="reportForm.user"
              readonly
              disabled
              placeholder="汇报人"
              class="input-width"
            />
          </el-form-item>

          <el-form-item label="报告分组" prop="report_group_id">
            <el-cascader
              ref="groupCascader"
              v-model="reportForm.report_group_id"
              :options="groupDataList"
              :props="cascaderProps"
              placeholder="选择报告分组"
              :show-all-levels="false"
              @change="handleCascaderChange"
            />
            <span
              v-show="isShowSelectTip"
              class="selectTip"
            >请优先选择报告分组</span>
          </el-form-item>

          <el-form-item label="总结" prop="conclusion">
            <Editor
              ref="EditorRef"
              v-model="reportForm.conclusion"
              :disabled="EditorDisabled"
            />

            <el-button type="text" :disabled="EditorDisabled" @click="handleCopyCode">
              <el-image
                style="width: 16px; height: 15px"
                :src="require('@/assets/report/copy_code.png')"
              />
              <span class="copy-code">复制代码及结果</span>
            </el-button>

          </el-form-item>

          <el-form-item label="照片" prop="conclusion_picture">
            <el-upload
              ref="fileUpload"
              :disabled="uploadDisabled"
              action=""
              accept="image/jpg,image/jpeg,image/png,image/*"
              list-type="picture-card"
              :auto-upload="false"
              :file-list="uploadFilesList"
              :limit="uploadFilesListLimit"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :on-exceed="uploadImgExceed"
            >
              <i slot="default" class="el-icon-plus" />
              <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                >
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in" />
                  </span>

                  <span
                    v-if="!fileDisabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete" />
                  </span>
                </span>
              </div>
            </el-upload>
          </el-form-item>

        </el-form>
      </div>

      <div slot="footer" class="footer">
        <el-button
          :disabled="isDisableSubmitForm || reportStatus === 1"
          class="footer__btn"
          type="primary"
          :loading="loading"
          @click="submitForm"
        >{{ reportStatus === 1 ? '已点评':'提 交' }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import Editor from '@/components/editor/index'
import BaseDialogHead from '@/components/BaseDialogHead'
import { report_group_list, post_report, get_report_detail } from '@/api/report'
import cosUploadTraverse from '@/utils/cosUploadTraverse'
import { fileUtils } from '@/utils/fileType'
import SHA256 from 'crypto-js/sha256'
import { dialogDataRest, fileProcess, extname } from '@/utils'

export default {
  name: 'UploadReport',
  // import引入的组件需要注入到对象中才能使用
  components: {
    BaseDialogHead,
    Editor
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 检测是否重名
    // var checkNameExist = async(rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('请填写矿池名称'))
    //   }
    //   // 检测名称是否重复
    //   const category = 1
    //   const check_type = 2
    //   await validateNameExist(value, category, check_type, callback)
    // }
    // 这里存放数据
    return {
      fileUtils,
      cosObj: {}, // cos所需要参数
      groupDataList: [], // 分组列表
      // select参数
      cascaderProps: {
        label: 'name',
        value: 'id',
        children: 'child',
        checkStrictly: false, // 开启互不关联
        emitPath: false // value 只为选中那个id，如果true则返回选中以及父级id的数组
      },
      alreadyExistUrl: [],
      uploadFilesList: [],
      uploadFilesListLimit: 8,
      // 表单
      reportForm: {
        user: '',
        conclusion_picture: '',
        report_group_id: Number,
        conclusion: ''
      },
      // 校验规则
      rules: {
        report_group_id: { required: true, message: '不能为空', trigger: 'blur' },
        conclusion: { required: true, message: '不能为空', trigger: 'blur' }
      },
      loading: false,
      // 预览图片url
      dialogImageUrl: '',
      // 控制预览图片
      dialogVisible: false,
      // 控制预览图片
      fileDisabled: false,
      // 控制上传组建
      uploadDisabled: true,
      // 控制富文本
      EditorDisabled: true,
      // 控制选择提示
      isShowSelectTip: true,
      // 控制提交按钮
      isDisableSubmitForm: false,
      // status 点评枚举值，1已点评，2未点评,初始化0
      reportStatus: 0
    }
  },
  // 监听属性 类似于data概念
  computed: {
  },
  // 监控data中的数据变化
  watch: {
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 生命周期 - keep-alive
  async activated() {},
  // 方法集合
  methods: {
    // 图片校验
    verifyPictureFormat(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'png', 'jpeg', 'gif']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$messageOnce.error('上传文件只能是图片')
        return false
      } else {
        return file
      }
    },
    // 复制代码和结果
    handleCopyCode() {
      const { code, CompileResultsOutput, CompileResultsError } = this.$parent
      const { conclusion } = this.reportForm

      // 如果没有编写代码 && 没有编译结果
      if (code.length === 0 && CompileResultsOutput.length === 0) {
        this.$messageOnce.error('代码不能为空，请完善代码')
        return false
      }

      // 新增直接赋值
      if (conclusion.length === 0) {
        this.reportForm.conclusion = `
        运行代码：<br /><pre>${code}</pre><br /><br />运行结果：<br /><pre>${CompileResultsOutput}</pre>
        `
      } else {
        // 有内容就追加
        this.reportForm.conclusion += `<br /><br />
        运行代码：<br /><pre>${code}</pre><br /><br />运行结果：<br /><pre>${CompileResultsOutput}</pre>
        `
      }

      // 光标插入到最后
      const tinymceEdit = this.$refs.EditorRef.tinymceEdit
      tinymceEdit.execCommand('selectAll')
      tinymceEdit.selection.getRng().collapse(false)
      tinymceEdit.focus()
      // 在最后添加一个 空格，触发滚动条
      tinymceEdit.insertContent('')
    },
    async getReportGroupList() {
      console.log('getReportGroupList 217')
      const MY_INFO_STR = localStorage.getItem('MY_INFO')
      const { real_name } = JSON.parse(MY_INFO_STR)
      this.reportForm.user = real_name
      // 说明：1：Solidity2：golang
      const { code, data } = await report_group_list({ ltype: '2' })
      if (code === 0) {
        console.log(data, '111111111')
        this.groupDataList = data
      }
    },
    // 实现缩略图模板时删除文件
    handleRemove(file) {
      // 如果上传按钮为 disbale 不可以删除图片
      const uploadDisabled = this.uploadDisabled

      if (uploadDisabled === true) { return false }

      const fileList = this.$refs.fileUpload.uploadFiles
      const index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      })
      fileList.splice(index, 1)
      // 删除data里面的数据
      this.uploadFilesList.splice(index, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      // 校验文件格式
      const isVerifyPictureFormat = this.verifyPictureFormat(file)
      if (isVerifyPictureFormat === false) {
        // 移除最后一个
        fileList.pop()
        return false
      }
      if (fileList.length > this.uploadFilesListLimit) {
        return false
      }
      this.uploadFilesList = fileList
    },
    // 对文件名进行sha256计算
    async handleSha245FileName() {
      const fileList = this.uploadFilesList

      const signedFileList = await Promise.all(
        fileList.map((val, index) => {
          return new Promise((resolve, reject) => {
            const fileType = extname(val.name)
            const reader = new FileReader()
            reader.readAsDataURL(val.raw)
            reader.onload = () => {
              const result = reader.result
              const signData = SHA256(result).toString()

              val.name = `${signData}.${fileType}`
              resolve(val)
            }
          })
        }))
      return await signedFileList
    },
    handlePreview(file) { },
    uploadImgExceed() {
      this.$messageOnce({
        message: `最多只能上传${this.uploadFilesListLimit}张图片`,
        type: 'warning',
        center: true,
        offset: 100
      })
    },
    async handleCascaderChange(value) {
      // 切换报告分组时，判断是否提交内容
      // this.handleToggleSave(value)
      try {
        // 关闭提示
        this.isShowSelectTip = false
        // 开启编辑
        this.EditorDisabled = false
        // 开启上传文件
        this.uploadDisabled = false
        this.loading = true
        const res = await get_report_detail(value)
        const { code, data } = res
        if (code === 0) {
          this.handleReportDetailData(data)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
      // this.$refs.groupCascader.toggleDropDownVisible()
    },
    // 切换报告分组时，判断是否提交内容
    handleToggleSave(value) {
      // 如果改变了 value ，则证明了有内容，需要保存一下
      // 图片列表
      const uploadFilesList = this.uploadFilesList
      // 凡文本
      const { conclusion } = this.reportForm
      // 报告状态
      const reportStatus = this.reportStatus

      // 等于1表示已阅读，直接切换分组
      if (reportStatus === 1) {
        return true
      } else {
        //
      }
      // console.log(uploadFilesList, conclusion, reportStatus)

      // 如果
    },
    // 过滤URL
    formatExistUrl(list) {
      const unExistList = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].raw) {
          unExistList.push(list[i])
        } else {
          this.alreadyExistUrl.push(list[i].url.replace('https://', ''))
        }
      }
      return unExistList
    },
    async handleReportDetailData(data) {
      if (data !== null) {
        // status 点评枚举值，1已点评，2未点评
        const { conclusion_picture, conclusion, status } = data
        this.reportForm.conclusion = conclusion

        // 在upload组建返现图片
        await this.handleShowCosImage(conclusion_picture)

        // 根据状态，控制按钮disable
        this.handleReportStatus(status)
      } else {
        // 等于null 清楚数据
        this.handleResetReportDetailData()
      }
    },
    // 等于null 清楚数据
    handleResetReportDetailData() {
      this.reportForm.conclusion_picture = ''
      this.reportForm.conclusion = ''
      this.uploadFilesList = []
      this.$refs.fileUpload.uploadFiles = []
      this.handleReportStatus(0)
    },
    // 根据状态，控制按钮disable
    handleReportStatus(status) {
      // 上传按钮
      this.reportStatus = status
      this.isDisableSubmitForm = status === 1
      // 编辑按钮
      this.EditorDisabled = status === 1
      // 上传文件按钮
      this.uploadDisabled = status === 1
    },
    // 在upload组建返现图片
    async handleShowCosImage(conclusion_picture) {
      const testArray = await Promise.all(
        conclusion_picture.map(async(val, index) => {
          const imgUrl = `https://${val}`
          const file = await fileProcess(imgUrl)
          const res = {
            url: imgUrl,
            uid: file.lastModified,
            name: file.name,
            raw: file,
            size: file.size,
            status: 'success'
          }

          return res
        }))

      // 赋值上传组建，返现图片
      this.uploadFilesList = testArray
      this.$refs.fileUpload.uploadFiles = testArray
    },
    // 对预览文件进行处理
    async handleFileList() {
      // 对文件进行计算，hash256为文件名称
      const fileList = await this.handleSha245FileName()
      // 队列上传
      const countConf = await cosUploadTraverse(fileList)
      // 证明文件没有错误
      if (countConf.fail === 0) {
        await this.postReportData(countConf)
      } else {
        // 证明上传文件有出错
        this.$messageOnce({
          message: '图片上传失败',
          type: 'error',
          duration: 2000
        })
      }
    },
    async postReportData(countConf) {
      try {
        const { successList } = countConf

        // 字符串
        // let conclusion_picture = ''
        // successList.forEach(el => {
        //   conclusion_picture += el.sourceUrl + ';'
        // })
        // // 去掉最后一个;
        // conclusion_picture = conclusion_picture.slice(0, conclusion_picture.length - 1)
        // console.log('conclusion_picture')
        // console.log(conclusion_picture)

        // 数组
        const conclusion_picture = successList.map((val) => {
          return val.sourceUrl
        })
        const postData = {
          ...this.reportForm,
          conclusion_picture
        }
        await post_report(postData)

        this.$messageOnce({
          message: '报告提交成功！',
          type: 'success'
        })

        // // 调用父组件方法更新 table
        // await this.$parent.getMenuList()

        // 向父组件关闭弹窗
        this.handleCloseDialog()
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3])
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([])
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.handleFileList()
        } else {
          this.$messageOnce({
            message: '请完善信息',
            type: 'error'
          })
          return false
        }
      })
    },
    handleCloseDialog() {
      dialogDataRest('ruleForm', 'rules', this)
      this.$emit('close')
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next((vm) => {})
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>
<style lang="scss" scoped>
.UploadReport {
  .fromcontent {
    height: 70vh;
    overflow-y: scroll;
  }

  .fromcontent::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  /*滚动条的轨道*/
  .fromcontent::-webkit-scrollbar-track {
    background-color: transparent;
  }
  /*滚动条的滑块按钮*/
  .fromcontent::-webkit-scrollbar-thumb {
    width: 8px;
    height: 238px;
    background: #D9D9D9; // 滚动条颜色
    border-radius: 5px;
  }
  /*滚动条的上下两端的按钮*/
  .fromcontent::-webkit-scrollbar-button {
    height: 0;
  }

  .PersonalInfo__ruleForm {
    padding: 30px;

    .subtitle {
      width: 100px;
      height: 30px;
      background: $MainColor;
      border-radius: 30px;
      font-size: 12px;
      font-weight: 500;
      color: #ffffff;
      text-align: center;
      line-height: 30px;
    }

    .modules-area {
      margin-top: 20px;

      .modules-item {
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 12px;
        cursor: pointer;
        height: 110px;
        width: 100%;

        .name {
          font-size: 14px;
          font-weight: 500;
          color: #141414;
          line-height: 21px;
        }

        .dec-item {
          position: absolute;
          left: 15px;
          top: 40px;
          width: 210px;

          .item-txt {
            white-space: pre-line;
            height: 32px;
            font-size: 12px;
            font-weight: 400;
            color: #8c8c8c;
            line-height: 16px;
          }
          .item-tips {
            margin-top: 12px;
            font-size: 12px;
            font-weight: 400;
            color: $MainColor;
            line-height: 14px;
            white-space: pre-line;
          }
        }
      }

      .modules-border {
        border: 1px solid $MainColor;
      }
    }

    .selectTip {
      color: $MainColor;
      padding-left: 20px;
      font-size: 14px;
    }

    .copy-code {
      font-size: 16px;
      font-weight: 500;
      margin-left: 12px;
      color: #2F54EB;
      line-height: 24px;
      position: relative;
      bottom: 2px;
    }
  }

  .footer {
    text-align: center;
    height: 80px;
    line-height: 80px;
    &__btn {
      @include SecondButton();
    }
  }

  ::v-deep .el-upload--picture-card {
    background-color: #fafafa;
    border: 1px dashed #C0C0C0;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    cursor: pointer;
    line-height: 100px;
    vertical-align: top;
  }

  ::v-deep .el-upload-list__item {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}

::v-deep .el-dialog__body {
  // padding: 30px 60px;
  padding: 0;
}

::v-deep .el-dialog__footer {
  padding: 0 60px;
  box-shadow: 0px -5px 20px 0px rgba(71, 73, 155, 0.06);
}
</style>
